<template>
  <div ref="container">
    <van-collapse class="sub-table" v-if="!!subForm" v-model="activeNames">
      <van-collapse-item name="1">
        <template #title>
          <SubTableHealder
              @addNew="addNew"
              @clear="clear"
              @copy="copy"
              :container="container"
              :context="context"
              :config="config"
              :subForm="subForm"
              :expanded="activeNames && activeNames.length"/>
        </template>
        <template #right-icon/>

        <SubTableList @copy="copy" @remove="remove" @edit="edit" :context="context" :config="config" :subForm="subForm" :dataSource="dataSource"/>
      </van-collapse-item>
    </van-collapse>

    <SubTableRowEditor
        :config="config"
        :context="context"
        :rowIndex="rowIndex"
        :subForm="subForm"
        :dataSource="dataSource"
        v-model:show="showEditor"
        :form-model="formModel"/>
  </div>
</template>
<script setup>
import SubTableHealder from '@comp/FormEngine/field/SubTable/SubTableHealder.vue';
import {createProps, getSubFormById, guid} from '@/utils';
import {computed, nextTick, ref, shallowRef} from 'vue';
import SubTableList from '@comp/FormEngine/field/SubTable/SubTableList.vue';
import SubTableRowEditor from '@comp/FormEngine/field/SubTable/SubTableRowEditor.vue';
import {showConfirmDialog} from 'vant';
import {AuthType} from '@comp/FormEngine/Constants';

defineOptions({name: 'SubTable'})
const activeNames = shallowRef(['1']);
const container = shallowRef();
const showEditor = shallowRef(false);
const props = defineProps({
  config: createProps(Object, () => undefined),
  context: createProps(Object, () => undefined),
})
const formModel = ref();
const rowIndex = shallowRef();

const subForm = computed(() => {
  if (!(props?.config?.subFormId) || !props?.context?.formDefinition || !props?.context?.formModel) return
  return getSubFormById(props?.config?.subFormId, props?.context?.formDefinition)
})

function addNew() {
  let formModel = {};
  createFields(formModel)
  dataSource.value.push(formModel);
  edit({
    formModel,
    rowIndex: dataSource.value.length - 1,
  });
  nextTick(() => {
    props?.context?.updateSubFormData()
  })
}

function createFields(data) {
  let fields = subForm.value?.fields || [];
  let auth = {}, fieldActions = props?.context?.action?.fieldActions || [];
  let required = {};
  fields.forEach(field => {
    let fieldAction = fieldActions.find(f => f.fieldId === field.id);
    auth[field.fieldName] = fieldAction && fieldAction.auth || AuthType.edit;
    required[field.fieldName] = fieldAction && fieldAction.required || false;

    if (field.fieldName) {
      data[field.fieldName] = undefined;
    }
    if (field.fieldTitleName) {
      data[field.fieldName] = undefined;
    }
  })
  data._auth = auth;
  data._required = required;
  data.id = guid();
  data._isNew = true;
}

function copy(formModel) {
  let row = JSON.parse(JSON.stringify(formModel));
  row.id = guid();
  row._isNew = true;
  dataSource.value.push(row);
  props?.context?.formFieldUpdate();
}
function clear() {
  showConfirmDialog({
    title: '确定清空吗',
    message: '清空后不可恢复, 确定清空吗',
  }).then(() => {
    dataSource.value = [];
  })
}

function edit(data) {
  formModel.value = data.formModel;
  rowIndex.value = data.rowIndex;
  openEditor()
}

function remove(index) {
  showConfirmDialog({
    title: '确定删除吗',
    message: '删除后不可恢复, 确定删除吗',
  }).then(() => {
    dataSource.value.splice(index, 1);
    props?.context?.formFieldUpdate();
  })
}

function openEditor() {
  showEditor.value = true;
}

const dataSource = computed({
  get() {
    if (!subForm.value) return [];
    return props.context.formModel[subForm.value.id]
  },
  set(v) {
    props.context.formModel[subForm.value.id] = v || [];
  }
})
</script>
<style lang="less">
@import "style";
</style>